import router from "@/router/index"
import { RouteRecordRaw } from "vue-router"
import { getFlatMenuList } from "@/utils/index"
import { useRouterStore } from "@/store/modules/routerControl"

// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/views/**/*.vue")

/**
 * @description 初始化动态路由
 */
export const initDynamicRouter = async () => {
  const routerStore = useRouterStore()
  try {
    // 添加动态路由
    getFlatMenuList(routerStore.initMenuList).forEach((item) => {
      item.children && delete item.children
      if (item.component && typeof item.component == "string") {
        item.component = modules["/src/views" + item.component + ".vue"]
      }
      if (item.meta.isFull) {
        router.addRoute(item as unknown as RouteRecordRaw)
      } else {
        router.addRoute("layout", item as unknown as RouteRecordRaw)
      }
    })
  } catch (error) {
    return Promise.reject(error)
  }
}
